package com.lingkun.demo.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingkun.demo.sys.entity.RoleMenu;
import com.lingkun.demo.sys.entity.SysMenu;
import com.lingkun.demo.sys.mapper.SysMenuMapper;
import com.lingkun.demo.sys.service.RoleMenuService;
import com.lingkun.demo.sys.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小龙
 * @since 2021-04-24
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

  @Autowired
  private RoleMenuService roleMenuService;

    @Override //通过角色id集合获取当前角色的所有可以访问的权限 jwt加入的权限
    public List<String> getPermission(List<String> users) {
    //查询出所有的权限id
        QueryWrapper<RoleMenu> wrapper1 =  new QueryWrapper<>();
             wrapper1.select("distinct menu_id");
             for (int i=0;i<users.size();i++){ wrapper1.in("role_id",users); }
             List<RoleMenu> list1 = roleMenuService.list(wrapper1);
    //通过权限id查询所以权限
        QueryWrapper<SysMenu> wrapper2 =  new QueryWrapper<>();
             wrapper2.select("distinct permission");
             List<String> roles =  new ArrayList<>();
        for (RoleMenu roleMenu : list1) {
            roles.add(roleMenu.getMenuId());
        }
             wrapper2.in("menu_id",roles);
             List<SysMenu> list2 = baseMapper.selectList(wrapper2);
             List<String> roles2 =  new ArrayList<>();
        for (SysMenu sysMenu : list2) {
            roles2.add(sysMenu.getPermission());
        }
             return roles2;
    }

    @Override     //根据一级菜单id获取二级菜单全部id
    public List<String> listMenuIds(String parent) {
        List<String>  list  =   baseMapper.listMenuIds(parent);
        return  list;

    }

    @Override   //获取可以访问改路由的角色id
    public List<String> searchMenuRoleIds(String mnName) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
          queryWrapper.select("menu_id").eq("path",mnName);
          String id =   baseMapper.selectOne(queryWrapper).getMenuId();
           List<String>  aa =   baseMapper.searchMenuRoleIds(id);
            return aa;
    }
}
